package com.distribution.system.manager.channel.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.distribution.common.exception.ServiceException;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.bo.*;
import com.distribution.system.domain.dto.ChoosePhoneDTO;
import com.distribution.system.domain.dto.SendCodeDTO;
import com.distribution.system.domain.entity.*;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.manager.channel.AbstractChannel;
import com.distribution.system.manager.channel.channelInfo.enums.ChuanHeChannelEnum;
import com.distribution.system.service.AddressChannelService;
import com.distribution.system.utils.http.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: GodLu
 * @create: 2024-04-27 14:49
 * @description: 川禾接口
 */
@Slf4j
public class ChuanHeChannel extends AbstractChannel {
    private static final Logger chOrderSearchLog = LoggerFactory.getLogger("chOrderSearchLog");

    public ChuanHeChannel(CmccDaUpChannelInfoBO cmccDaUpChannelInfoBO) {
        super(cmccDaUpChannelInfoBO);
    }

    @Override
    public AddressInfoBo getChannelAddressInfo(AddressNameBo addressNameBo, AddressChannelService addressChannelService) {
        return null;
    }

    @Override
    public String configPlaceOrderRequestParams(CmccDaOrder cmccDaOrder, CmccDaProduct cmccDaProduct, AddressInfoBo addressInfoBo) {
        log.info("配置川禾下单接口参数...");
        AddressChannel addressInfo = addressInfoBo.getAddressInfo();
        AddressChannel attributeInfo = addressInfoBo.getAttributeInfo();
        //配置请求参数
        Map<String, Object> map = getRequest();
        map.put("goodsId", cmccDaProduct.getProductParam());
        // numberInfo
        Map<String,Object> numberInfoMap = new HashMap<>();
        numberInfoMap.put("orderNumber", cmccDaOrder.getChoosePhone());//订购号码
        numberInfoMap.put("provinceCode", attributeInfo.getEssProvinceCode());//省份编码
        numberInfoMap.put("cityCode", attributeInfo.getEssCityCode());//城市编码
        if (!StringUtils.isEmpty(cmccDaOrder.getPhoneUuid())) {
            numberInfoMap.put("uuid", cmccDaOrder.getPhoneUuid());//选号接口返回的UUID，部分商品需要
        }
        map.put("numberInfo", numberInfoMap);
        // guesInfo
        Map<String,Object> guesInfoMap = new HashMap<>();
        guesInfoMap.put("name", cmccDaOrder.getCustomerName());//客户姓名
        guesInfoMap.put("certId", cmccDaOrder.getCustomerCertNo());//客户身份证
        guesInfoMap.put("phone", cmccDaOrder.getCustomerPhone());//客户联系方式
        if (!"1".equals(cmccDaProduct.getBroadbandFlag()) && "1".equals(cmccDaProduct.getCodeFlag())) {
            guesInfoMap.put("smsCode", cmccDaOrder.getCode());//验证码(部分产品需要)
        }
        map.put("guesInfo", guesInfoMap);
        Map<String,Object> addressInfoMap = new HashMap<>();
        addressInfoMap.put("webProvince", addressInfo.getProvinceCode());//6位收货省份编码
        addressInfoMap.put("webCity", addressInfo.getCityCode());//6位收货城市编码
        addressInfoMap.put("webCounty", addressInfo.getDistrictCode());//6位收货区县编码
        addressInfoMap.put("address", cmccDaOrder.getAddressProvince() + cmccDaOrder.getAddressCity() + cmccDaOrder.getAddressStreet());//详细地址
        map.put("addressInfo",addressInfoMap);
        // channelInfo
        Map<String,Object> channelInfoMap = new HashMap<>();
        // 生成订单号
        orderId = "CH" + DateUtil.format(DateUtil.date(), "yyyyMMdd") + IdUtil.getSnowflake(1, 1).nextIdStr().substring(8,18);
        channelInfoMap.put("outerId", orderId);//外部订单号
        map.put("channelInfo",channelInfoMap);
        //请求
        return new JSONObject(map).toString();
    }

    @Override
    public String sendPlaceOrderRequest(String requestJsonStr) {
        return HttpRequestUtils.sendPost(interfaceUrlsMap.get(ChuanHeChannelEnum.PLACE_ORDER.getName()), requestJsonStr);
    }

    @Override
    public ReqResult parsePlaceOrderResponseStr(JSONObject responseJsonObject) {
        if ("0025".equals(responseJsonObject.get("code"))){// 成功
            UnOrderResultBo unOrderResultBo = new UnOrderResultBo();
            unOrderResultBo.setOrderId(orderId);
            unOrderResultBo.setChannelOrderNo(responseJsonObject.getString("outid"));
            return ReqResult.success(responseJsonObject.getString("msg"), unOrderResultBo);
        } else {// 失败
            return ReqResult.error(responseJsonObject.getString("msg"));
        }
    }

    @Override
    public String configChoosePhoneRequestParams(ChoosePhoneDTO choosePhoneDTO, CmccDaProduct cmccDaProduct, AddressInfoBo addressInfoBo) {
        log.info("请求川禾选择号码接口...");
        Map<String, Object> map = getRequest();
        //配置请求参数
        map.put("goodsId", cmccDaProduct.getProductParam());
        map.put("provinceCode", addressInfoBo.getAttributeInfo().getEssProvinceCode());
        map.put("cityCode", addressInfoBo.getAttributeInfo().getEssCityCode());
        map.put("searchValue", StringUtils.isBlank(choosePhoneDTO.getKeywords()) ? "" : choosePhoneDTO.getKeywords());
        return new JSONObject(map).toString();
    }

    @Override
    public String sendChoosePhoneRequest(String requestJsonStr) {
        return HttpRequestUtils.sendPost(interfaceUrlsMap.get(ChuanHeChannelEnum.CHOOSE_PHONE.getName()), requestJsonStr);
    }

    @Override
    public ReqResult parseChoosePhoneResponseStr(JSONObject responseJsonObject) {
        String code = responseJsonObject.getString("code");
        String msg = responseJsonObject.getString("msg");
        if ("0000".equals(code)){
            ChoosePhoneResultBO choosePhoneResultBO = new ChoosePhoneResultBO();
            choosePhoneResultBO.setUuid(responseJsonObject.getString("uuid"));
            List<String> numArray = new ArrayList<>();
            JSONArray jsonArray = responseJsonObject.getJSONArray("numberArr");
            for (Object object : jsonArray) {
                String phoneNum = String.valueOf(object);
                if (!StringUtils.isEmpty(phoneNum)){
                    numArray.add(phoneNum);
                }
            }
            choosePhoneResultBO.setNumArray(numArray);
            return ReqResult.success(choosePhoneResultBO);
        } else if ("0001".equals(code)){
            return ReqResult.error(msg);
        } else {
            return ReqResult.error("选号流程未知错误，请联系系统管理员");
        }
    }

    @Override
    public ReqResult sendCardSmsCode(CmccDaProduct cmccDaProduct, SendCodeDTO sendCodeDTO) {
        Map<String, Object> map = getRequest();
        map.put("idcard",sendCodeDTO.getCertNum());
        map.put("phone",sendCodeDTO.getCustomerPhone());
        String requestJson = new JSONObject(map).toString();
        JSONObject responseJson = JSONObject.parseObject(HttpRequestUtils.sendPost(interfaceUrlsMap.get(ChuanHeChannelEnum.SEND_SMS.getName()), requestJson));
        if ("0025".equals(responseJson.getString("code"))) {// 成功
            return ReqResult.success(responseJson.getString("msg"));
        } else {// 失败
            return ReqResult.error(responseJson.getString("msg"));
        }
    }


    @Override
    public RefreshOrderBO getRefreshOrderBO(CmccDaOrder cmccDaOrder) {
        // 川禾是根据订单编号更新的
        String orderId = cmccDaOrder.getOrderId();
        Map<String,Object> requestMap = getRequest();
        requestMap.put("orderId", orderId);
        String requestJson = new JSONObject(requestMap).toString();
        chOrderSearchLog.info("【川禾】查单请求 => {}",requestJson);
        JSONObject responseJson = JSONObject.parseObject(HttpRequestUtils.sendPost(interfaceUrlsMap.get(ChuanHeChannelEnum.SELECT_ORDER.getName()), requestJson));
        chOrderSearchLog.info("【川禾】查单响应 => {}",responseJson.toString());
        if (!"0000".equals(responseJson.getString("code"))) {// 失败
            throw new ServiceException(responseJson.getString("msg"));
        }
        return parseToRefreshOrderBO(responseJson);
    }

    @Override
    public Map<CmccDaOrder, RefreshOrderBO> getRefreshOrderBOMap(List<CmccDaOrder> orderList) {
        List<CmccDaOrder> subList = orderList.subList(0, Math.min(100, orderList.size()));
        String orderIds = subList.stream().map(CmccDaOrder::getOrderId).collect(Collectors.joining(","));
        Map<String,Object> requestMap = getRequest();
        requestMap.put("orderId", orderIds);
        String requestJson = new JSONObject(requestMap).toString();
        chOrderSearchLog.info("【川禾】批量查单请求 => {}",requestJson);
        JSONObject responseJson = JSONObject.parseObject(HttpRequestUtils.sendPost(interfaceUrlsMap.get(ChuanHeChannelEnum.SELECT_ORDER_LIST.getName()), requestJson));
        chOrderSearchLog.info("【川禾】批量查单响应 => {}",responseJson.toString());
        if (!"0000".equals(responseJson.getString("code"))) {// 失败
            throw new ServiceException(responseJson.getString("msg"));
        }
        Map<CmccDaOrder, RefreshOrderBO> refreshOrderBOMap = new HashMap<>();
        responseJson.getJSONArray("data").forEach(f -> {
            JSONObject jsonObject = (JSONObject) f;
            RefreshOrderBO refreshOrderBO = parseToRefreshOrderBO(jsonObject);
            CmccDaOrder cmccDaOrder = orderList.stream().filter(a -> StringUtils.equals(a.getChannelOrderNo(), refreshOrderBO.getChannelOrderNo())).collect(Collectors.toList()).get(0);
            refreshOrderBOMap.put(cmccDaOrder, refreshOrderBO);
        });
        return refreshOrderBOMap;
    }
    private RefreshOrderBO parseToRefreshOrderBO(JSONObject jsonObject){
        RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
        refreshOrderBO.setPhone(jsonObject.getString("number"));// 订购号码
//            refreshOrderBO.setProductStatus(jsonObject.getString("orderstate"));//K计划订单返回激活状态，其他订单不返回
        refreshOrderBO.setProductStatus("-1");//K计划订单返回激活状态，其他订单不返回
        String status = "2";// 默认进行中
        if ("成功".equals(jsonObject.getString("suc"))){// 成功
            status = "3";
        }
        refreshOrderBO.setStatus(status);
        // 这里首冲金额单位是元，需要转换为分
        try {
            String doMoney = (String) jsonObject.get("domoney");
            String s = StringUtils.isEmpty(doMoney) ? "0" : (new BigDecimal(doMoney).multiply(new BigDecimal(100))).toString();
            refreshOrderBO.setScMoney(s);
        } catch (Exception e) {
            log.error("渠道方订单编号为{}的订单刷新状态时首冲金额由元转换为分时出错，原因{}", refreshOrderBO.getChannelOrderNo(),e.getMessage());
        }
        refreshOrderBO.setChannelOrderNo(jsonObject.getString("outid"));
        return refreshOrderBO;
    }

    public Map<String,Object> getRequest() {
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        String tripartiteApiAppId = interfaceParamsMap.get(ChuanHeChannelEnum.APP_ID.getName());
        String tripartiteApiAppKey = interfaceParamsMap.get(ChuanHeChannelEnum.APP_SECRET.getName());
        stringObjectHashMap.put("appid",tripartiteApiAppId);
        stringObjectHashMap.put("userKey",tripartiteApiAppKey);
        return stringObjectHashMap;
    }

    @Override
    public void refreshChannelCommission(CmccDaUpChannelInfo cmccDaUpChannelInfo) {
    }
}
